package com.etalk.crm.interceptor;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.etalk.crm.utils.EncryptAndDecrypt;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.http.HttpMethod;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * 接口token校验
 *
 * @author Terwer
 * @version 1.0
 * @date 2018/11/6 14:53
 **/
public class AuthHandlerInterceptor implements HandlerInterceptor {
    private static final Logger logger = LogManager.getLogger(AuthHandlerInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws IOException {
        logger.info("requestURI:" + request.getRequestURI());
        logger.info("requestMethod:" + request.getMethod());

        // 设置返回编码
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");

        // 跨域处理
        response.setHeader("Access-Control-Allow-Origin", "*");
        // 兼容入参为RequestBody时候的预请求
        if (request.getMethod().equals(HttpMethod.OPTIONS.name())) {
            response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
            return true;
        }

        //告诉浏览器编码方式
        response.setHeader("Content-Type", "text/html;charset=UTF-8");
        // 说明处在编辑的页面
        Object tokenString = request.getParameter("tokenString");
        //request.getParameter(arg0)
        if (!StringUtils.isEmpty(tokenString) && !tokenString.toString().trim().isEmpty()) {
            logger.info("token:" + EncryptAndDecrypt.decrypt(tokenString.toString()));
            JSONObject jsonObject = JSON.parseObject(EncryptAndDecrypt.decrypt(tokenString.toString()));
            if (!StringUtils.isEmpty(jsonObject)) {
                request.getSession().setAttribute("person.id", jsonObject.getIntValue("loginId"));
                request.getSession().setAttribute("person.loginName", jsonObject.getString("loginName"));
                request.getSession().setAttribute("person.roleId", jsonObject.getIntValue("roleId"));
                request.getSession().setAttribute("person.storeId", jsonObject.getIntValue("storeId"));
                return true;
            }
        }

        //tokenString错误，返回错误信息
        try (PrintWriter out = response.getWriter()) {
            Map<String, Object> map = new HashMap<>(3);
            map.put("status", 0);
            Map<String, Integer> dataMap = new HashMap<>();
            dataMap.put("errorCode", 10001);
            map.put("data", dataMap);
            map.put("msg", "tokenString为空或错误");
            out.append(JSON.toJSONString(map));
            logger.info("tokenString错误，tokenString=" + tokenString);
        } catch (IOException e) {
            logger.error("请求错误：", e);
        }
        return false;
    }
}
